#include "WindowOperations.h"

WindowOperations * WindowOperations::instance = NULL;

WindowOperations::~WindowOperations() {
	delete instance;
}

LRESULT CALLBACK WindowOperations::windowCallbackProcedure(HWND pHWindow, UINT pMessage, WPARAM pWParam, LPARAM pLParam) {
	if (instance == NULL) {
		instance = new WindowOperations();
	}
	return instance->windowProcedure(pHWindow, pMessage, pWParam, pLParam);
}

LRESULT CALLBACK WindowOperations::windowProcedure(HWND pHWindow, UINT pMessage, WPARAM pWParam, LPARAM pLParam) {
	switch (pMessage) {
	case WM_KEYDOWN:
		if (pWParam == VK_ESCAPE) {
			DestroyWindow(pHWindow);
		}
		return 0;
	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	}
	return DefWindowProc(pHWindow, pMessage, pWParam, pLParam);
}

void WindowOperations::showDefaultErrorMessage(const TCHAR *pMessage) {
	MessageBox(NULL, pMessage, TurnsDataModel::WINDOW_ERROR_TITLE, MB_OK);
}

void WindowOperations::showWin32ErrorMessage() {
	LPTSTR lpszFunction = (LPTSTR)TurnsDataModel::WINDOW_ERROR_FUNCTION;
	LPVOID lpMsgBuf;
	LPVOID lpDisplayBuf;
	DWORD dw = GetLastError();

	FormatMessage(
		FORMAT_MESSAGE_ALLOCATE_BUFFER |
		FORMAT_MESSAGE_FROM_SYSTEM |
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		dw,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(LPTSTR)&lpMsgBuf,
		0, NULL);

	lpDisplayBuf = (LPVOID)LocalAlloc(
		LMEM_ZEROINIT,
		(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR)
		);
	StringCchPrintf(
		(LPTSTR)lpDisplayBuf,
		LocalSize(lpDisplayBuf) / sizeof(TCHAR),
		TurnsDataModel::WINDOW_ERROR_FORMAT_MESSAGE,
		lpszFunction,
		dw,
		lpMsgBuf
		);
	MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TurnsDataModel::WINDOW_ERROR_TITLE, MB_OK);
}
